package org.chen.controller;

import lombok.extern.slf4j.Slf4j;
import org.chen.model.sys.ImageResource;
import org.chen.response.Result;
import org.chen.service.impl.ConfigServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Slf4j
public class UploadController {

    @Autowired
    private ConfigServiceImpl configService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String uploadPath = configService.getConfigValue("article.admin.upload-path");
            String accessPath = configService.getConfigValue("article.admin.access-path");

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + suffix;

            // 计算MD5
            String md5 = DigestUtils.md5DigestAsHex(file.getInputStream());

            // 检查是否存在相同图片
            ImageResource existingImage = mongoTemplate.findOne(
                    Query.query(Criteria.where("md5").is(md5).and("isDeleted").is(false)),
                    ImageResource.class
            );

            if (existingImage != null) {
                return Result.success(Map.of("url", existingImage.getUrl()));
            }

            // 确保目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean mkdirs = uploadDir.mkdirs();
            }

            // 保存文件
            File destFile = new File(uploadDir, filename);
            file.transferTo(destFile);

            // 保存资源信息
            ImageResource resource = new ImageResource();
            resource.setFileName(filename);
            resource.setOriginalName(originalFilename);
            resource.setType("ADMIN");
            resource.setCreateTime(new Date());
            resource.setPath(destFile.getAbsolutePath());
            resource.setUrl(accessPath + "/" + filename);
            resource.setSize(file.getSize());
            resource.setMd5(md5);
            resource.setIsDeleted(false);

            mongoTemplate.save(resource);

            return Result.success(Map.of("url", resource.getUrl()));

        } catch (Exception e) {
            log.error("Upload file failed", e);
            throw new RuntimeException("Upload file failed", e);
        }
    }
}